//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows;
using OpenLS.Core;
using OpenLS.Spreadsheet.Debugging;


namespace OpenLS.Spreadsheet.UI
{
    /// <summary>
    /// Interaction logic for BugReportWindow.xaml
    /// </summary>
    public partial class BugReportWindow : Window
    {
        private SpreadsheetDocument doc;

        private string DocumentPath =
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "KhertyBugReports.xlsx");

        public BugReportWindow()
        {
            InitializeComponent();
        }

        private void OnLoaded(object sender, object args)
        {
            try
            {
                doc = SpreadsheetDocument.Open(DocumentPath);
            }
            catch
            {
                doc = SpreadsheetDocument.Create();
                int i = 0;
                Worksheet ws = doc.Workbook.Sheets[0] as Worksheet;
                
                if (ws == null)
                    return;
                foreach (
                    string s in
                        new string[] {"User name", "OS version", "Spr version", "Date", "Type", "Description", "Log"})
                {
                    ws[0, i].Value = s;
                    i++;
                }
                doc.SaveAs(DocumentPath);
            }
            DataContext = doc;
            fileName.Text = DocumentPath;
            type.Focus();
        }

        private void OnInsert(object sender, object args)
        {
            Debug.WriteLine("Adding bug report");
            Worksheet ws = doc.Workbook.Sheets[0] as Worksheet;
            int i;
            for (i = 1; ws[i, 0].Value != null; i++)
            {
            }
            ws[i, 0].Value = Environment.UserName;
            ws[i, 1].Value = Environment.OSVersion.Platform.ToString() + Environment.OSVersion.ServicePack +
                             Environment.OSVersion.VersionString;
            ws[i, 2].Value = Assembly.GetEntryAssembly().FullName;
            ws[i, 3].Value = DateTime.Now;
            ws[i, 3].Format = Format.Parse("yyyy/m/d hh:mm");
            ws[i, 4].Value = type.Text;
            ws[i, 5].Value = description.Text;
            using (TextReader reader = new StreamReader(DebugTraceListener.Instance.FileName))
            {
                ws[i, 6].Value = reader.ReadToEnd();
                ws[i, 6].TextWrapping = TextWrapping.Wrap;
            }
            ws.ActiveCell = ws[i, 0];
            ws.Selection = new SingleCellRange(ws.ActiveCell);
            ws.TopLeftPane.EnsureVisible(ws[i, 0]);
            doc.Save();
        }
    }
}